/**
 * create by young (young2f@outlook.com) on 2020/9/12
 */


'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {Calendar, Select,Form, Radio, Col, Row,} from 'antd';
import {ModalView} from 'antd-extra';
const { Group, Button } = Radio;
import styles from '../index.less';
import DirTree from '../../components/DirTree';
import FormBase from '../../components/Base/FormBase';
import notify from "../../components/NotificationExtra";
import moment from "moment";

import Badge from "antd/es/badge";

import ModalUploadPic from "./modal/ModalUploadPic";

const _ = require('lodash');

const table = 'DayExperiment';

@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            material,
            treeNode
          }) => ({...user, ...global, ...material, ...dynamicLabel, ...treeNode}))
export default class Index extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table, tenantCode: this.getTenantCode()},
    });
    this.onDataLoad().then(res => {
      this.setState({pics: res});
    });

  }

  async onDataLoad() {
    const {treeNode} = this.state;
    if (!treeNode) return;
    const {treeId} = treeNode;
    const res = await this.props.dispatch({
      type: 'dic/findPicMany',
      payload: {treeId},
    });

    return res.result;
  }

  onTreeNodeSelected = (node) => {
    if (!node) return;
    this.state.treeNode = node;
    this.componentDidMount();
  };
//todo
  onTreeDelete = (_id, result) => {

  };


  onPanelChange = (value, mode) => {
    console.log(value, mode);
  };
  dateCellRender = (day) => {

    const {pics = [], treeNode} = this.state;
    const {treeId} = treeNode;
    return (
      <ul className="events">
        {pics.map(item => {
          const {date, fileList} = item;
          if (moment(day).format("YYYY-MM-DD") === moment(date).format("YYYY-MM-DD") && treeId === item.treeId) {
            return <div>
              {
                fileList.map(file =>
                  <li key={item.content}>
                    <Badge color={"green"} text={file.name}/></li>
                )

              }
            </div>;
          }
        })}
      </ul>
    );

  };

  dataPage = () => {
    return <Form>
      <div style={{  border: '1px solid #d9d9d9', borderRadius: 4 }}>
        <Calendar
          fullscreen={true}
          headerRender={({ value, type, onChange, onTypeChange }) => {
            const start = 0;
            const end = 12;
            const monthOptions = [];

            const current = value.clone();
            const localeData = value.localeData();
            const months = [];
            for (let i = 0; i < 12; i++) {
              current.month(i);
              months.push(localeData.monthsShort(current));
            }

            for (let index = start; index < end; index++) {
              monthOptions.push(
                <Select.Option className="month-item" key={`${index}`}>
                  {months[index]}
                </Select.Option>,
              );
            }
            const month = value.month();

            const year = value.year();
            const options = [];
            for (let i = year - 10; i < year + 10; i += 1) {
              options.push(
                <Select.Option key={i} value={i} className="year-item">
                  {i}
                </Select.Option>,
              );
            }
            return (
              <div style={{ padding: 10 }}>
                {/*<div style={{ marginBottom: '10px' }}>Custom header </div>*/}
                <Row type="flex" justify="space-between">
                  <Col>
                    <Group size="small" onChange={e => onTypeChange(e.target.value)} value={type}>
                      {/*<Button value="month">Month</Button>*/}
                      {/*<Button value="year">Year</Button>*/}
                    </Group>
                  </Col>
                  <Col>
                    <Select
                      size="small"
                      dropdownMatchSelectWidth={false}
                      className="my-year-select"
                      onChange={newYear => {
                        const now = value.clone().year(newYear);
                        onChange(now);
                      }}
                      value={String(year)}
                    >
                      {options}
                    </Select>
                  </Col>
                  <Col>
                    <Select
                      size="small"
                      dropdownMatchSelectWidth={false}
                      value={String(month)}
                      onChange={selectedMonth => {
                        const newValue = value.clone();
                        newValue.month(parseInt(selectedMonth, 10));
                        onChange(newValue);
                      }}
                    >
                      {monthOptions}
                    </Select>
                  </Col>
                </Row>
              </div>
            );
          }}
          dateCellRender={this.dateCellRender}
          onPanelChange={this.onPanelChange}
          onSelect={(value) => {
            const {pics = [], treeNode} = this.state;
            const {treeId} = treeNode;

            console.log(treeNode, moment(value).format('YYYY-MM-DD'));
            const record = _.find(pics, pic => {
              return (moment(pic.date).format("YYYY-MM-DD") === moment(value).format('YYYY-MM-DD')) && (pic.treeId === treeId);
            });

            ModalView.open(ModalUploadPic,
              {
                title: '图片文件',
                width: '960px',
              }, {
                record,
                callback: (payload) => {
                  payload.treeId = treeId;
                  payload.date = moment(value).format('YYYY-MM-DD');
                  const type = record ? 'dic/updateOnePic' : 'dic/createPic';
                  const code = record ? record.code : undefined;
                  payload.code = code;
                  this.props.dispatch({
                    type,
                    payload,
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });
                }
              });
          }}
        />
      </div>,
    </Form>;

  };

  render() {
    const {dispatch, expandedKeys, _notify} = this.props;
    if (_notify) {
      notify(_notify);
    }
    let title = '每日填报';
    return (
      <Form className={styles.content}>
        <DirTree
          disableEdit={false}
          table={table}
          dispatch={dispatch}
          onTreeDelete={this.onTreeDelete}
          onTreeNodeSelected={this.onTreeNodeSelected}
          expandedKeys={expandedKeys}
          defaultExpandAll={true}
          title={title}
        > {this.dataPage()}</DirTree>

      </Form>
    );
  }
}
